package com.shiguiwu.springmybatis.netty.simple;

import com.shiguiwu.springmybatis.netty.simple.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: netty 客户端
 * @author: stone
 * @date: Created by 2021/12/5 19:03
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.netty.simple
 */
@Slf4j
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        //新建客户端,需要一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            log.info("client is ok!!!");

            //启动客户端去连接服务器端  关于 ChannelFuture 要分析，涉及到netty的异步模型
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8999).sync();
            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();

        }

    }
}
